using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services
{
    public class OrderItemService : BaseService<OrderItem>, IOrderItemService
    {
        private readonly IOrderService _orderService;

        public OrderItemService(PandaSystemContext context, IOrderService orderService) : base(context)
        {
            _orderService = orderService;
        }

        public async Task<List<OrderItem>> GetOrderItemsByOrderIdAsync(Guid orderId)
        {
            return await _dbSet
                .Include(i => i.Product)
                .Where(i => i.OrderId == orderId)
                .OrderBy(i => i.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<OrderItem>> GetOrderItemsByProductIdAsync(Guid productId)
        {
            return await _dbSet
                .Include(i => i.Order)
                .Where(i => i.ProductId == productId)
                .OrderByDescending(i => i.CreatedAt)
                .ToListAsync();
        }

        public async Task<OrderItem> UpdateQuantityAsync(Guid orderItemId, int quantity)
        {
            var orderItem = await _dbSet
                .Include(i => i.Order)
                .FirstOrDefaultAsync(i => i.OrderItemId == orderItemId);

            if (orderItem == null)
                throw new KeyNotFoundException($"Order item with ID {orderItemId} not found.");

            if (quantity <= 0)
                throw new ArgumentException("Quantity must be greater than zero.");

            orderItem.Quantity = quantity;
            await _context.SaveChangesAsync();

            // 更新订单总金额
            await _orderService.CalculateOrderTotalAsync(orderItem.OrderId);

            return orderItem;
        }

        public async Task<decimal> CalculateItemTotalAsync(Guid orderItemId)
        {
            var orderItem = await _dbSet.FindAsync(orderItemId);
            if (orderItem == null)
                throw new KeyNotFoundException($"Order item with ID {orderItemId} not found.");

            return orderItem.Quantity * orderItem.UnitPrice;
        }

        public override async Task<OrderItem> CreateAsync(OrderItem orderItem)
        {
            // 设置默认值
            orderItem.OrderItemId = Guid.NewGuid();
            orderItem.CreatedAt = DateTime.UtcNow;

            // 验证数量
            if (orderItem.Quantity <= 0)
                throw new ArgumentException("Quantity must be greater than zero.");

            // 验证单价
            if (orderItem.UnitPrice <= 0)
                throw new ArgumentException("Unit price must be greater than zero.");

            await _dbSet.AddAsync(orderItem);
            await _context.SaveChangesAsync();

            // 更新订单总金额
            await _orderService.CalculateOrderTotalAsync(orderItem.OrderId);

            return orderItem;
        }

        public override async Task<OrderItem> UpdateAsync(OrderItem orderItem)
        {
            var existingItem = await _dbSet
                .Include(i => i.Order)
                .FirstOrDefaultAsync(i => i.OrderItemId == orderItem.OrderItemId);

            if (existingItem == null)
                throw new KeyNotFoundException($"Order item with ID {orderItem.OrderItemId} not found.");

            // 只允许更新特定字段
            existingItem.Quantity = orderItem.Quantity;
            existingItem.UnitPrice = orderItem.UnitPrice;

            // 验证数量
            if (existingItem.Quantity <= 0)
                throw new ArgumentException("Quantity must be greater than zero.");

            // 验证单价
            if (existingItem.UnitPrice <= 0)
                throw new ArgumentException("Unit price must be greater than zero.");

            await _context.SaveChangesAsync();

            // 更新订单总金额
            await _orderService.CalculateOrderTotalAsync(existingItem.OrderId);

            return existingItem;
        }

        public override async Task<bool> DeleteAsync(Guid id)
        {
            var orderItem = await _dbSet
                .Include(i => i.Order)
                .FirstOrDefaultAsync(i => i.OrderItemId == id);

            if (orderItem == null)
                return false;

            var orderId = orderItem.OrderId;
            _dbSet.Remove(orderItem);
            await _context.SaveChangesAsync();

            // 更新订单总金额
            await _orderService.CalculateOrderTotalAsync(orderId);

            return true;
        }
    }
} 